'use strict';

const Service = require('egg').Service;

class UserService extends Service {

  // 注册用户
  async createUser(payload) {
    const { app, ctx } = this;
    const { password } = payload;
    payload = Object.assign(payload, payload.password = await ctx.genHash(password));
    const transaction = await app.model.transaction();
    try {
      const res_user = await app.model.User.create(payload, { transaction });
      const defaultRole = await app.model.Role.findOne({ where: { is_default: 1 } });
      // 分配默认角色
      await app.model.UserRole.create(
        {
          user_id: res_user.id,
          role_id: defaultRole.id,
        },
        { transaction }
      );
      await transaction.commit();
      return res_user;
    } catch (error) {
      await transaction.rollback();
      console.error('error', error);
    }
  }

  // 获取用户列表
  async getUserList(pageNum, pageSize) {
    const { app } = this;
    try {
      const offset = (pageNum - 1) * pageSize;
      const { count, rows } = await app.model.User.findAndCountAll({
        attributes: { exclude: [ 'password', 'paypassword' ] },
        order: [
          [ 'createdAt', 'desc' ],
        ],
        include: [
          {
            model: this.app.model.Role,
            as: 'roles',
            attributes: [ 'name' ], // 只显示哪些字段
            through: { attributes: [] }, // 排除中间表
          },
          {
            model: this.app.model.Article,
            as: 'articles',
            attributes: [ 'id', 'title' ],
          },
        ],
        offset,
        limit: pageSize * 1,
      });
      return {
        pageNum,
        pageSize,
        total: count,
        list: rows,
      };
    } catch (error) {
      console.error(error);
      return null;
    }
  }

  // 获取用户用户信息
  async getUserInfo({ ...args }) {
    const whereOpt = { ...args };
    const res = await this.app.model.User.findOne({
      // attributes: { exclude: [ 'password', 'paypassword' ] },
      include: {
        model: this.app.model.Role,
        as: 'roles',
        attributes: [ 'name' ], // 只显示哪些字段
        through: { attributes: [] }, // 排除中间表
        // include: [
        //   {
        //     model: this.app.model.Permission,
        //     attributes: [ 'id', 'url', 'action' ],
        //   },
        // {
        //   model: this.app.model.Article,
        //   as: 'articles',
        //   attributes: [ 'id', 'title' ],
        // },
        // ],
      },
      where: whereOpt,
    });
    return res ? res.dataValues : null;
  }

  // 修改用户信息
  async updatedUser(id, user) {
    delete user.user_name;// 不允许修改用户名
    const { app } = this;
    return await app.model.User.update(user, { where: { id } });
  }
  // 修改用户密码
  async updatedUserPwd(id, password) {
    const newUser = { id, password };
    const { app } = this;
    return await app.model.User.update(newUser, { where: { id } });
  }
  // 修改用户密码
  async upPayPassword(id, paypassword) {
    const newUser = { id, paypassword };
    const { app } = this;
    return await app.model.User.update(newUser, { where: { id } });
  }

  // 删除用户
  async removeUser(payload) {
    const { app } = this;
    return await app.model.User.destroy({ where: { id: payload.ids } });
  }

  // 给用户设置角色
  async setRoles(payload) {
    const { app } = this;
    const { user_id, role_id } = payload;
    // return await app.model.UserRole.create({ user_id, role_id });
    try {
      return await app.model.UserRole.create({ user_id, role_id });
    } catch (error) {
      return false;
    }
  }


}

module.exports = UserService;
